<template>
  <div class="upload-wrapper">
    <a-upload
      :disabled="isDisabled"
      name="file"
      :accept="accept"
      :multiple="multiple"
      :action="uploadAction"
      :headers="headers"
      :fileList="fileList"
      :list-type="listType"
      :remove="removeFile"
      method="post"
      :before-upload="beforeUpload"
      :showUploadList="showUploadList"
      @change="handleUpload"
      @preview="previewFile">
      <a-button v-if="listType!=='picture-card'&&fileList.length<maxNum" :disabled="isDisabled" :loading="loading">
        <a-icon type="upload"/>
        {{ btnTitle || '上传' }}
      </a-button>
      <div v-if="listType==='picture-card'&&fileList.length<maxNum">
        <a-icon type="plus"/>
        <div>{{ btnTitle || '上传' }}</div>
      </div>
    </a-upload>
    <div v-if="showHint" class="upload-hint" :style="{'margin-top':listType!=='picture-card'?'10px':'0'}">
      {{ hint }}
    </div>
  </div>
</template>

<script>
import storage from "@/utils/storage";
import {appConfig} from "@/config/app";
import {baseUrl} from "@/config";
import {isEmpty} from "@/utils/func";
import {previewFile} from "@/utils/func";

export default {
  name: "Upload",
  props: {
    defaultFileList: {
      type: Array,
      required: false,
      default: () => [],
    },
    listType: {
      type: String,
      default: 'text'
    },
    showHint: {
      type: Boolean,
      default: false,
      required: false,
    },
    multiple: {
      type: Boolean,
      required: false,
      default: false,
    },
    isDisabled: {
      type: Boolean,
      required: false,
      default: false,
    },
    maxSize: {
      type: Number,
      required: false,
      default: 20
    },
    maxNum: {
      type: Number,
      required: false,
      default: 0
    },
    imgWH:{
      type: String,
      default: ''
    },
    // 是否显示文件列表  默认显示
    showUploadList: {
      type: Boolean,
      required: false,
      default: true
    },
    btnTitle: {
      type: String,
      required: false
    },
    accept: {
      type: String,
      required: false,
      default: '.doc,.docx,.zip,.rar,.pdf,.csv,.xls,.xlsx,.jpg,.png'
    },
	// wps
    hint: {
      type: String,
      required: false,
      default: '支持扩展名：.doc,.docx,.zip,.rar,.pdf,.csv,.xls,.xlsx,.jpg,.png'
    }
  },
  data() {
    return {
      uploadAction: "",
      headers: {
        Authorization: "Bearer " + storage.session.get("authToken"),
      },
      loading: false,
      //上传成功附件ID数组
      storageFileIds: [],
      //已经上传的文件列表
      fileList: []
    }
  },
  watch: {
    defaultFileList: {
      handler(newVal) {
        console.log(newVal,'newVal')
        this.fileList = []
        this.fileList.unshift(...this.defaultFileList)
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.uploadAction = baseUrl + appConfig.microServModules.file + "api/fdfs/file/upload";
  },
  methods: {
    checkImg(file){
      return new Promise((res)=>{
        if(!this.imgWH)return res(true)
        let [w,h] = this.imgWH.split('*')
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          const img = new Image();
          img.src = reader.result;
          img.onerror = () => res(false)
          img.onload = () => res(img.width == w && img.height == h)
        };
      })
    },
    // 上传前调用
    async beforeUpload(file) {
      let checkImg = await this.checkImg(file)
      const acceptList = this.accept.split(',')
      const isAccepted = acceptList.some(item => {
        item = item.toLocaleLowerCase()
        let fileName = file.name.toLocaleLowerCase()
        return fileName.endsWith(item)
      })
      if (!isAccepted) {
        this.$message.error('仅支持上传扩展名为：' + this.accept + '的文件')
        return Promise.reject()
      }

      if (this.$checkFileIsIllegal(file.name)) {
        this.$message.info('文件类型非法')
        return Promise.reject()
      }

      if(!checkImg){
        this.$message.error(`上传分辨率为${this.imgWH}的图片`);
        return Promise.reject()
      }

      if (this.maxNum > 0 && this.fileList.length >= this.maxNum) {
        this.$message.error(`上传数量限制为${this.maxNum}`);
        return Promise.reject()
      }
      const validSize = (file.size / 1024 / 1024) > this.maxSize;
      if (validSize) {
        this.$message.error(`文件大小不能超过${this.maxSize}M`);
        return Promise.reject()
      }
      return Promise.resolve(file) 
    },
    downloadFile(file) {
      let storageFileId = file.storageFileId || (file.response ? file.response.data.storageFileId : '')
      if (storageFileId) {
        window.open(
          appConfig.microServ +
          appConfig.microServModules.file +
          "api/fdfs/file/download?storage_file_id=" + storageFileId
        );
      } else {
        if (file.url) {
          window.open(file.url)
        } else {
          this.$message.error('文件地址路径不完整')
        }
      }
    },
    // 附件预览
    previewFile(file) {
      if (file.url) {
        if (previewFile(file.url)) {
          window.open(file.url)
        } else {
          this.downloadFile(file)
        }
      } else {
        this.$message.error('文件地址路径不完整')
      }

      // let storageFileId = file.storageFileId || (file.response ? file.response.data.storageFileId : '');
      // if (storageFileId) {
      //   window.open(
      //     appConfig.microServ +
      //     appConfig.microServModules.file +
      //     "api/fdfs/file/download?storage_file_id=" +
      //     storageFileId
      //   );
      // } else {
      //   if (file.url) {
      //     window.open(file.url)
      //   } else {
      //     this.$message.error('文件地址路径不完整')
      //   }
      // }
    },
    // 附件上传
    handleUpload(info) {
      this.loading = info.file.status === 'uploading';
      // 上传失败
      if (info.file.status !== 'removed' && (info.file.response && info.file.response.code != 0)) {
        info.file.status = 'error'
        const index = info.fileList.findIndex(item => item.uid === info.file.uid)
        this.$set(info.fileList, index, info.file)
        this.$message.error(`${info.file.name}上传失败，原因：${info.file.response.message}`);
      }
      info.fileList = info.fileList.filter(file => {
        return !isEmpty(file.status)
      })

      this.fileList = info.fileList;

      let fileList = [...info.fileList];

      fileList = fileList.map(file => {
        if (file.response && file.response.data) {
          file.url = file.response.data.fileUrl;
        }
        return file;
      });
      if (info.file.status === 'done' || info.file.status === 'removed') {
        this.storageFileIds = [];
        for (let val of fileList) {
          if (val.storageFileId) {
            this.storageFileIds.push(val.storageFileId);
          } else {
            if (val.response && val.response.data)
              this.storageFileIds.push(val.response.data.storageFileId);
          }
        }
        if (info.file.status === 'done') {
          this.$message.success(`文件上传成功`);
        }
        this.$emit("change", this.storageFileIds, fileList);
      }
      // else if (info.file.status === 'error') {
      //   this.$message.error(`${info.file.name} 文件上传失败.`);
      // }
    },
    removeFile(file) {
      file.status = 'removed'
      const index = this.fileList.findIndex(item => item.uid === file.uid)
      this.$set(this.fileList, index, file)
      return true
    }
  }
}
</script>

<style scoped lang="scss">
.upload-wrapper {
  line-height: normal !important;
}

.upload-hint {
  color: #999999;
  font-family: PingFang-SC-Medium, PingFang-SC, sans-serif;
  font-size: 12px;
  line-height: 12px;
}
</style>
